<template>
  <div class="arrange">
    <el-row>
      <el-col :span="20">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="影院名称">
            <el-input
              v-model="formInline.cinemaName"
              placeholder="影院名称"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="queryPanel">查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="4" style="text-align: right">
        <el-button
          type="primary"
          icon="el-icon-circle-plus-outline"
          @click="dialogVisible = true"
        >添加影厅</el-button>
      </el-col>
    </el-row>
    <div class="table">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="index" width="50" />
        <el-table-column prop="movieName" label="电影名称" width="280" />
        <el-table-column prop="cinemaScreen" label="影院影厅" />
        <el-table-column prop="statrDate" label="开始时间" width="220" />
        <el-table-column prop="endDate" label="结束时间" width="220" />
        <el-table-column label="操作" width="140">
          <template slot-scope="scope">
            <el-link
              type="primary"
              :underline="false"
              style="margin-right: 15px"
              @click="edit(scope.row)"
            >
              编辑
            </el-link>
            <el-link
              type="danger"
              :underline="false"
              @click="remove(scope.row.id)"
            >
              删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog
      :title="isEdit ? '编辑排片' : '添加排片'"
      :visible.sync="dialogVisible"
      width="40%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :before-close="close"
    >
      <div class="form-box" style="display: flex; justify-content: center">
        <el-form
          ref="arrangeDataRef"
          :model="arrangeData"
          :rules="arrangeDataRules"
          label-width="90px"
          class="demo-ruleForm"
          label-position="left"
        >
          <el-form-item label="电影名称" prop="movieName">
            <el-select
              v-model="arrangeData.movieName"
              placeholder="请选择电影"
              @change="getScreenType"
            >
              <el-option
                v-for="item in allMovies"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="影院影厅" prop="cinemaScreen">
            <!-- <el-select
              v-model="arrangeData.cinemaScreen"
              placeholder="请选择电影"
              @change="getScreenType"
            >
              <el-option
                v-for="item in allScreen"
                :key="item.id"
                :label="item.cinemaName"
                :value="item.cinemaName"
              />
            </el-select> -->
            <el-cascader
              v-model="arrangeData.cinemaScreen"
              placeholder="影院影厅"
              :options="options"
              filterable
            />
          </el-form-item>
          <el-form-item label="开始时间" prop="statrDate">
            <el-date-picker
              v-model="arrangeData.statrDate"
              type="datetime"
              placeholder="选择开始时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="结束时间" prop="endDate">
            <el-date-picker
              v-model="arrangeData.endDate"
              type="datetime"
              placeholder="选择结束时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button
          type="primary"
          @click="save('arrangeDataRef')"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Arrange',

  data() {
    return {
      isEdit: false,
      dialogVisible: false,
      allScreen: [],
      options: [],
      formInline: {
        cinemaName: '',
        screenName: ''
      },
      screenList: [
        {
          id: '1',
          movieName: '流浪地球2',
          cinemaScreen: ['万达影城（高新区店）', '1号厅'],
          statrDate: '2023-04-05 16:00:00',
          endDate: '2023-04-05 18:00:00'
        },
        {
          id: '2',
          movieName: '满江红',
          cinemaScreen: ['中影星美国际影城（闽侯店）', '2号厅'],
          statrDate: '2023-04-05 16:00:00',
          endDate: '2023-04-05 18:00:00'
        }
      ],
      tableData: [],
      allMovies: [],
      arrangeData: {
        id: new Date().getTime(),
        movieName: '',
        cinemaScreen: '',
        statrDate: '',
        endDate: ''
      },
      screenType: [],
      arrangeDataRules: {
        movieName: [
          { required: true, message: '请选择电影名称', trigger: 'change' }
        ],
        cinemaScreen: [
          { required: true, message: '请选择影院影厅', trigger: 'change' }
        ],
        statrDate: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endDate: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ]
      }
    }
  },
  async created() {
    const allArrange = await this.$localStorage.getItem('allArrange')
    if (!allArrange) {
      await this.$localStorage.setItem('allArrange', this.screenList)
    }
  },
  async mounted() {
    const allMovies = await this.$localStorage.getItem('allMovies')
    this.allMovies = allMovies
    const allScreen = await this.$localStorage.getItem('allScreen')
    this.allScreen = allScreen
    this.tableData = await this.$localStorage.getItem('allArrange')
    // console.log(this.allMovies);
    console.log(this.tableData)

    const data = {}
    allScreen.map((item) => {
      if (data[item.cinemaName]) {
        data[item.cinemaName].push(item.screenName)
      } else {
        data[item.cinemaName] = [item.screenName]
      }
    })
    const options = []
    for (const key in data) {
      const obj = {
        value: key,
        label: key,
        children: []
      }
      data[key].forEach((item) => {
        const o = {
          value: item,
          label: item
        }
        obj.children.push(o)
      })
      options.push(obj)
    }
    this.options = options
    console.log(options)
  },

  methods: {
    async queryPanel() {
      const allArrange = await this.$localStorage.getItem('allArrange')

      const { cinemaName, screenName } = this.formInline

      const newData = allArrange.filter((item) => {
        if (
          item.cinemaName.includes(cinemaName) &&
          item.screenName.includes(screenName)
        ) {
          return item
        }
      })

      this.tableData = newData
      // console.log(movieName, movieType, hotnew);
    },
    close() {
      this.arrangeData = {
        id: new Date().getTime(),
        movieName: '',
        cinemaScreen: '',
        statrDate: '',
        endDate: ''
      }
      this.dialogVisible = false
      this.isEdit = false
    },
    edit(data) {
      this.isEdit = true
      this.arrangeData = Object.assign({}, data)
      this.getScreenType(data.cinemaName, true)
      this.dialogVisible = true
    },
    remove(id) {
      this.$confirm('此操作将删除该排片, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const newData = this.tableData.filter((item) => item.id !== id)
          this.tableData = newData
          await this.$localStorage.setItem('allArrange', newData)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {})
    },
    save(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          if (this.isEdit) {
            const newData = this.tableData.map((item) => {
              if (item.id === this.arrangeData.id) {
                return this.arrangeData
              }
              return item
            })
            this.tableData = newData
            await this.$localStorage.setItem('allArrange', this.tableData)
          } else {
            debugger
            this.tableData.unshift(this.arrangeData)
            await this.$localStorage.setItem('allArrange', this.tableData)
          }
          this.close()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getScreenType(val, bool) {
      //   this.screenType = [];
      //   if (!bool) this.arrangeData.screenType = [];
      //   this.allMovies.find((item) => {
      //     if (val === item.cinemaName) {
      //       return (this.screenType = item.cinemaType);
      //     }
      //   });
    }
  }
}
</script>

<style lang="scss" scoped>
.arrange {
  padding: 20px 100px;
  .el-tag {
    margin-right: 10px;
    margin-bottom: 5px;
  }
}
.form-box {
  padding: 0 50px;
  form {
    width: 100%;
    .el-select {
      width: 100%;
    }
    .el-date-editor {
      width: 100%;
    }
    .el-cascader {
      width: 100%;
    }
  }
}
</style>
